import { useRef, useState } from 'react'
import {
  NavBar,
  Form,
  DatePicker,
  Radio,
  TextArea,
  Button,
  ImageUploader,
  Toast,
  Card,
  Modal,
} from 'antd-mobile'
import type { TextAreaRef } from 'antd-mobile'
import { useNavigate, useParams } from 'react-router-dom'
import styles from './index.module.css'
import { uploadFile, completeLeaseInspection } from '../../services/api'

type ImageUploadItem = { url: string; file?: File; [key: string]: any }

export default function LeaseAudit() {
  const navigate = useNavigate()
  const { id } = useParams()
  const [visible, setVisible] = useState(false)
  const [date, setDate] = useState<Date | null>(null)
  const [canReassign, setCanReassign] = useState<'yes' | 'no' | null>(null)
  const [reason, setReason] = useState<'q1' | 'q2' | null>(null)
  const [otherReason, setOtherReason] = useState('')
  const [files, setFiles] = useState<ImageUploadItem[]>([])
  const [confirmVisible, setConfirmVisible] = useState(false)
  const [submitting, setSubmitting] = useState(false)
  const [pendingPayload, setPendingPayload] = useState<any>(null)
  const otherInputRef = useRef<TextAreaRef>(null)

  const safeToast = (content: string, icon?: 'success' | 'fail' | 'loading' | 'info') => {
    try {
      Toast.show({ icon, content })
    } catch (e) {
      window.alert(content)
    }
  }

  const uploader = async (file: File) => {
    const proxy = (import.meta as any).env?.VITE_PROXY_TARGET as string | undefined
    const res = await uploadFile(file)
    const url = proxy ? `${proxy}${res.link || ''}` : res.link
    return { url, link: res.link, name: res.originalName || res.name || file.name }
  }

  const formatDateTime = (d: Date) => {
    const y = d.getFullYear()
    const m = `${d.getMonth() + 1}`.padStart(2, '0')
    const day = `${d.getDate()}`.padStart(2, '0')
    // 时分秒固定 00:00:00
    return `${y}-${m}-${day} 00:00:00`
  }

  const onSubmit = async () => {
    if (!date) {
      safeToast('请选择退房日期', 'fail')
      return
    }
    if (!canReassign) {
      safeToast('请选择是否可再次分配', 'fail')
      return
    }
    if (canReassign === 'no' && !reason) {
      safeToast('请选择原因', 'fail')
      return
    }
    if (canReassign === 'no' && reason === 'q2' && !otherReason.trim()) {
      safeToast('请输入其他原因', 'fail')
      return
    }

    const reasonTextMap: any = { q1: '房屋存在质量问题暂无法分配', q2: '其他原因' }
    const payload = {
      leaseId: (id as any) || 0,
      files: files
        .map((f: any) => f?.link || '')
        .filter((s: string) => !!s)
        .join(','),
      returnTime: date ? formatDateTime(date) : '',
      isAllocate: canReassign === 'yes' ? 1 : 0,
      reasonAllocate:
        canReassign === 'no'
          ? reason === 'q2'
            ? otherReason.trim()
            : reason
            ? reasonTextMap[reason]
            : ''
          : '',
    }
    setPendingPayload(payload)
    setConfirmVisible(true)
  }

  return (
    <div className={styles['lease-audit-page']}>
      <NavBar back onBack={() => navigate(-1)}>
        审核
      </NavBar>

      <div className={styles['lease-audit-section']}>
        <Form footer={null}>
          <Card style={{ borderRadius: 12 }}>
            <div className={styles['lease-audit-block']}>
              <div className={styles['lease-audit-title']}>退房日期：</div>
              <Form.Item
                className={`${styles['lease-date-item']} ${date ? styles['is-selected'] : ''}`}
                onClick={() => setVisible(true)}
              >
                <DatePicker
                  visible={visible}
                  value={date ?? undefined}
                  onClose={() => setVisible(false)}
                  onConfirm={val => {
                    setVisible(false)
                    setDate(val)
                  }}
                >
                  {() => (date ? date.toLocaleDateString?.() : '请选择退房日期')}
                </DatePicker>
              </Form.Item>
            </div>

            <div className={styles['lease-audit-block']}>
              <div className={styles['lease-audit-title']}>该房屋能否再次分配：</div>
              <Form.Item>
                <Radio.Group
                  value={canReassign as any}
                  onChange={val => {
                    const v = val as 'yes' | 'no'
                    setCanReassign(v)
                    if (v === 'yes') {
                      setReason(null)
                      setOtherReason('')
                    }
                  }}
                >
                  <div className={styles['lease-audit-radios']}>
                    <Radio value="yes">是</Radio>
                    <Radio value="no">否</Radio>
                  </div>
                </Radio.Group>
              </Form.Item>
            </div>

            <div className={styles['lease-audit-block']}>
              <div className={styles['lease-audit-title']}>请选择原因：</div>
              <Form.Item className={canReassign === 'yes' ? styles['disabled'] : ''}>
                <Radio.Group
                  value={reason as any}
                  onChange={val => {
                    const v = val as 'q1' | 'q2'
                    setReason(v)
                    if (v === 'q1') {
                      setOtherReason('')
                    } else {
                      setTimeout(() => otherInputRef.current?.focus(), 0)
                    }
                  }}
                >
                  <div className={styles['lease-audit-reasons']}>
                    <div className={styles['lease-audit-reason']}>
                      <Radio value="q1">房屋存在质量问题暂无法分配</Radio>
                    </div>
                    <div className={styles['lease-audit-reason']}>
                      <Radio value="q2">其他原因</Radio>
                    </div>
                  </div>
                </Radio.Group>
              </Form.Item>
              <Form.Item>
                <TextArea
                  ref={otherInputRef}
                  value={otherReason}
                  onChange={setOtherReason}
                  placeholder="请输入其他原因"
                  rows={2}
                  disabled={canReassign === 'yes' || reason !== 'q2'}
                />
              </Form.Item>
            </div>

            <div className={styles['lease-audit-block']}>
              <div className={styles['lease-audit-title']}>附件：</div>
              <Form.Item>
                <ImageUploader
                  value={files}
                  onChange={setFiles}
                  upload={uploader}
                  multiple
                  maxCount={9}
                />
              </Form.Item>
            </div>
          </Card>
        </Form>
      </div>

      <div className={styles['lease-audit-bottom']}>
        <Button
          size="large"
          className={`${styles['lease-audit-btn']} ${styles['primary']}`}
          onClick={onSubmit}
        >
          立即提交
        </Button>
      </div>

      <Modal
        visible={confirmVisible}
        showCloseButton
        onClose={() => setConfirmVisible(false)}
        content={<div style={{ paddingTop: 6, paddingBottom: 6 }}>是否同意当前退租请求？</div>}
        actions={[
          {
            key: 'reject',
            text: '拒绝',
            onClick: async () => {
              if (!pendingPayload) return
              try {
                setSubmitting(true)
                await completeLeaseInspection({ ...pendingPayload, state: 0 })
                safeToast('已拒绝', 'success')
                setConfirmVisible(false)
                navigate('/lease')
              } finally {
                setSubmitting(false)
              }
            },
          },
          {
            key: 'agree',
            text: submitting ? '提交中...' : '同意',
            onClick: async () => {
              if (!pendingPayload) return
              try {
                setSubmitting(true)
                await completeLeaseInspection({
                  ...pendingPayload,
                  state: 1,
                  content: '物业端验房完成',
                })
                safeToast('已同意', 'success')
                navigate('/lease')
              } finally {
                setConfirmVisible(false)
                setSubmitting(false)
              }
            },
          },
        ]}
      />
    </div>
  )
}
